﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.PressReleases
{
    public static class Index
    {
        public static Adams.Admin.DataTransfer.PressReleases.Index.PageLoad PageLoad()
        {
            var data = new Adams.Admin.DataTransfer.PressReleases.Index.PageLoad();
            
            return data;
        }

        public static Adams.Admin.DataTransfer.PressReleases.Index.GridLoad GridLoad(DataTransfer.GridLoadInput gridinput)
        {
            var data = new Adams.Admin.DataTransfer.PressReleases.Index.GridLoad();
            data.Records = new Shared.Entities.PressReleases.PressReleaseCollection();

            string filter = string.IsNullOrWhiteSpace(gridinput.Search) ? string.Empty : "FREETEXT ((Title,ShortDescription,LongDescription), '" + gridinput.Search.Replace("'", "''") + "' )";

            string dbq = DB.BuildPagingQuery(gridinput.StartRow, gridinput.PageSize,
                "PressReleaseID,Title,ShortDescription,ReleaseDate",
                "PressReleases.PressReleases",
                filter, string.Empty, gridinput.Sort + " " + gridinput.SortDirection, "PressReleaseID");

            using (SqlDataReader dr = DB.RunDataReader(dbq, CommandType.Text))
            {
                dr.Read();
                data.TotalRecords = dr[0].DbInt();

                dr.NextResult();
                while (dr.Read())
                {
                    var PressRelease = new Shared.Entities.PressReleases.PressRelease();
                    PressRelease.ID = dr["PressReleaseID"].DbInt();
                    PressRelease.Title = dr["Title"].DbString();
                    PressRelease.ShortDescription = dr["ShortDescription"].DbString();
                    PressRelease.ReleaseDate = dr["ReleaseDate"].DbDate();
                    data.Records.Add(PressRelease);
                }
            }

            return data;
        }

        public static void Delete(int id)
        {
            DB.Run(@"
DELETE PressReleases.PressReleases
WHERE PressReleaseID = @PressReleaseID
", CommandType.Text,
                    DB.CreateParameter("@PressReleaseID", id, SqlDbType.Int));
        }
    }
}
